package com.sunday.shoufen.ui;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.sunday.common.alipay.PayResult;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.shoufen.R;
import com.sunday.shoufen.base.Constants;
import com.sunday.shoufen.entity.ConfirmBuy;
import com.sunday.shoufen.entity.PayInfo;
import com.sunday.shoufen.http.ApiClient;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by 刘涛 on 2017/10/20.
 */

public class OrderPayActivity extends BaseActivity {

    @Bind(R.id.title_view)
    TextView titleView;
    @Bind(R.id.pro_money)
    TextView proMoney;
    @Bind(R.id.total_money)
    TextView totalMoney;
    @Bind(R.id.dicount1)
    TextView dicount1;
    @Bind(R.id.my_score)
    TextView myScore;
    @Bind(R.id.btn_select_integral)
    ImageView btnSelectIntegral;
    @Bind(R.id.rl_select_integral)
    RelativeLayout rlSelectIntegral;
    @Bind(R.id.dicount2)
    TextView dicount2;
    @Bind(R.id.my_coupon_balance)
    TextView myCouponBalance;
    @Bind(R.id.btn_select_coupon)
    ImageView btnSelectCoupon;
    @Bind(R.id.rl_select_coupon)
    RelativeLayout rlSelectCoupon;
    @Bind(R.id.ll_select_discount)
    LinearLayout llSelectDiscount;
    @Bind(R.id.ll_select_coupon_balance)
    LinearLayout llSelectCoupon;
    @Bind(R.id.select_my_coupon)
    TextView selectMyCoupon;
    @Bind(R.id.select_coupon_pay)
    CheckBox selectCouponPay;
    @Bind(R.id.select_pay_way)
    TextView selectPayWay;
    @Bind(R.id.wechat_pay)
    CheckBox wechatPay;
    @Bind(R.id.alipay)
    CheckBox alipay;
    @Bind(R.id.total_money_bottom)
    TextView totalMoneyBottom;
    @Bind(R.id.total_money_bottom_extra)
    TextView totalMoneyBottomExtra;
    @Bind(R.id.confirm_pay)
    Button confirmPay;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @Bind(R.id.buy_num)
    TextView buyNum;
    @Bind(R.id.txt_no_coupon)
    TextView txtNoCoupon;

    private ConfirmBuy confirmBuy;
    private int proNum = 1;

    private int payType = 2;//1:支付宝 2：微信
    private IWXAPI api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_pay);
        ButterKnife.bind(this);
        confirmBuy = (ConfirmBuy) getIntent().getSerializableExtra("confirmBuy");
        proNum = getIntent().getIntExtra("proNum", 1);
        initView();
    }


    private int discountType = 1;//优惠方式(1-返消费积分 2-返通用券)
    private BigDecimal ticketFee = BigDecimal.ZERO;//通用券抵用额

    @SuppressLint("DefaultLocale")
    private void initView() {
        titleView.setText("确认支付");
        proMoney.setText("￥" + confirmBuy.getAmount());
        totalMoney.setText("￥" + confirmBuy.getAmount());
        buyNum.setText(String.valueOf(proNum));
        totalMoneyBottomExtra.setText("￥" + confirmBuy.getAmount());
        if (confirmBuy.getIsAddActive() == 0) {
            llSelectDiscount.setVisibility(View.GONE);
            discountType = 1;
            llSelectCoupon.setVisibility(View.GONE);
            btnSelectIntegral.setImageResource(R.mipmap.ic_select);
            btnSelectCoupon.setImageResource(R.mipmap.ic_select_no);
        } else {
            if (confirmBuy.getCommissionScale() == 0) {
                rlSelectIntegral.setVisibility(View.GONE);
            }
            if (confirmBuy.getTicketMoney().compareTo(BigDecimal.ZERO) < 1) {
                llSelectCoupon.setVisibility(View.GONE);
                txtNoCoupon.setVisibility(View.VISIBLE);
                selectCouponPay.setVisibility(View.GONE);
                discountType = 2;
                btnSelectIntegral.setImageResource(R.mipmap.ic_select);
                btnSelectCoupon.setImageResource(R.mipmap.ic_select_no);

            } else {
                txtNoCoupon.setVisibility(View.GONE);
                selectCouponPay.setVisibility(View.VISIBLE);
                discountType = 2;
                btnSelectIntegral.setImageResource(R.mipmap.ic_select_no);
                btnSelectCoupon.setImageResource(R.mipmap.ic_select);
            }

            dicount1.setText(new StringBuilder().append(String.format("赚消费积分%.2f", confirmBuy.getCommissionScale() * 100)).append("%").toString());
            myScore.setText(String.format("当前积分%s", confirmBuy.getMemberScore().setScale(2, RoundingMode.HALF_UP)));
            dicount2.setText(new StringBuilder().append(String.format("领活动通用券%.2f", confirmBuy.getCouponCommission() * 100)).append("%").toString());
            myCouponBalance.setText(String.format("当前余额%s", confirmBuy.getTicketMoney().setScale(2, RoundingMode.HALF_UP)));
            selectMyCoupon.setText(String.format("当前余额%s", confirmBuy.getTicketMoney().setScale(2, RoundingMode.HALF_UP)));
        }

        wechatPay.setChecked(true);
        CheckChangedListener checkChangedListener = new CheckChangedListener();
        alipay.setOnCheckedChangeListener(checkChangedListener);
        wechatPay.setOnCheckedChangeListener(checkChangedListener);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.registerApp(Constants.APP_ID);

        selectCouponPay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    BigDecimal bd = new BigDecimal(confirmBuy.getAmount());
                    ticketFee = bd.compareTo(confirmBuy.getTicketMoney()) > 0 ? confirmBuy.getTicketMoney() : bd;
                    if ((bd.subtract(ticketFee)).compareTo(BigDecimal.ZERO) > 0) {
                        totalMoneyBottomExtra.setText(String.format("￥%s",
                                (bd.subtract(ticketFee)).setScale(2, RoundingMode.HALF_UP)));
                    } else {
                        totalMoneyBottomExtra.setText("￥0.01");
                    }
                } else {
                    ticketFee = BigDecimal.ZERO;
                    totalMoneyBottomExtra.setText("￥" + confirmBuy.getAmount());
                }
            }
        });


    }

    private class CheckChangedListener implements CompoundButton.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                alipay.setChecked(false);
                wechatPay.setChecked(false);
                switch (buttonView.getId()) {
                    case R.id.wechat_pay:
                        wechatPay.setChecked(true);
                        payType = 2;
                        break;
                    case R.id.alipay:
                        alipay.setChecked(true);
                        payType = 1;
                        break;
                }
            } else {
                payType = 0;
            }
        }
    }

    @OnClick({R.id.btn_select_integral, R.id.btn_select_coupon, R.id.confirm_pay})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_select_integral:
                discountType = 1;
                llSelectCoupon.setVisibility(View.GONE);
                btnSelectIntegral.setImageResource(R.mipmap.ic_select);
                btnSelectCoupon.setImageResource(R.mipmap.ic_select_no);
                selectCouponPay.setChecked(false);
                ticketFee=BigDecimal.ZERO;
                break;
            case R.id.btn_select_coupon:
                discountType = 2;
                llSelectCoupon.setVisibility(View.VISIBLE);
                btnSelectIntegral.setImageResource(R.mipmap.ic_select_no);
                btnSelectCoupon.setImageResource(R.mipmap.ic_select);
                break;
            case R.id.confirm_pay:
                if (payType == 0) {
                    ToastUtils.showToast(mContext, "请选择支付类型");
                    return;
                }
                if (confirmBuy.getIsAddActive() == 1 && ticketFee.compareTo(BigDecimal.ZERO) > 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("温馨提示");
                    builder.setMessage("使用卡券余额支付将无法领取活动通用券");
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setPositiveButton("确定支付", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            getPayInfo();
                        }
                    });
                    builder.show();
                } else {
                    getPayInfo();
                }

                break;
        }
    }

    private PayInfo payInfo;

    private void getPayInfo() {
        showLoadingDialog(0);
        Call<ResultDO<PayInfo>> call = ApiClient.getApiAdapter().getPayInfos(confirmBuy.getOrderNo(), payType, ticketFee, discountType);
        call.enqueue(new Callback<ResultDO<PayInfo>>() {
            @Override
            public void onResponse(Call<ResultDO<PayInfo>> call, Response<ResultDO<PayInfo>> response) {
                dissMissDialog();
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    payInfo = response.body().getResult();
                    if (payInfo == null) {
                        return;
                    }
                    switch (payType) {
                        case 2:
                            wechatPay();
                            break;
                        case 1:
                            alipay();
                            break;
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }

            }

            @Override
            public void onFailure(Call<ResultDO<PayInfo>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void wechatPay() {
        PayReq req = new PayReq();
        req.appId = payInfo.getAppId();
        req.partnerId = payInfo.getParterId();
        req.prepayId = payInfo.getPrepayId();
        req.nonceStr = payInfo.getNonceStr();
        req.timeStamp = payInfo.getTimeStamp();
        req.packageValue = "Sign=WXPay";
        req.sign = payInfo.getPaySign();
        req.extData = "app data";
        api.sendReq(req);
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;

    private void alipay() {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(OrderPayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo.getAlipayStr());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    //Log.e("支付宝信息",payResult.toString());
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(mContext, "支付成功",
                                Toast.LENGTH_SHORT).show();
                        intent = new Intent(mContext, PaySuccessActivity.class);
                        startActivity(intent);
                        intent.putExtra("payMoney", confirmBuy.getAmount());
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(mContext, "检查结果为：" + msg.obj,
                            Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

    };
}
